package cn.zxh.csdn_maven.atomy.auth;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.HttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.zxh.csdn_maven.atomy.auth.GetSourceList.AbstractSource;
import cn.zxh.csdn_maven.base.util.GetHtmlFromUrl;

public class DownLoadSource extends AbstractSource{

	@Override
	public Map<String, Object> execute(HttpClient client, Map<String, Object> params) throws Exception {
		Map<String, Object> resulMap = new HashMap<String, Object>();
		List<String> downLoadRealUrl = new ArrayList<String>();
		String baseUrl = getBaseUrl();
		if(params==null){
			params=new HashMap<String, Object>();
		}
		if(params!=null&&params.get("times")!=null){
			baseUrl+="/"+params.get("times").toString();
		}
		params.put("base_url",baseUrl);
		String html = GetHtmlFromUrl.getInstance().getHtml(params);
		Document document = Jsoup.parse(html);
		Elements elements = document.select("div[class=item uresource]>ul>li");
		for (Element element : elements) {
			String href = element.select("div[class=img rar1]>a").attr("href");
			/**获取下载地址前缀*/
			String suffix="";
			String regex="(.*)/my.*";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(baseUrl);
			while(matcher.find()){
				suffix+=matcher.group(1);
			}
			downLoadRealUrl.add(suffix+href);
		}
		if(params!=null&&params.get("times")==null){
			/**获取页数，提供给父类循环爬取彻底*/
			Element timElement = document.select("div.page_nav").get(0);
			String times="";
			String regex=".*共(\\d+)页.*";
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(timElement.text());
			while(matcher.find()){
				times+=matcher.group(1);
			}
			resulMap.put("times",times);
		}
		resulMap.put("download",downLoadRealUrl);
		return resulMap;
	}

	@Override
	public String getBaseUrl() {
		return "http://download.csdn.net/my/uploads";
	}

}
